package com.dianrui.qiyouriding.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.blankj.utilcode.util.SPUtils;
import com.dianrui.qiyouriding.Constant;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.adapter.SecretProtocolAdapter;
import com.dianrui.qiyouriding.baidumap.BaiDuUtils;
import com.dianrui.qiyouriding.baidumap.LocationBaiduClient;
import com.dianrui.qiyouriding.bean.BikePointModel;
import com.dianrui.qiyouriding.bean.CarPointBean;
import com.dianrui.qiyouriding.bean.StationBean;
import com.dianrui.qiyouriding.bean.TargetInfoModel;
import com.dianrui.qiyouriding.event.PaymentEvent;
import com.dianrui.qiyouriding.event.RfreshLocation;
import com.dianrui.qiyouriding.event.RfreshOrder;
import com.dianrui.qiyouriding.util.CountDownTimerUtils;
import com.dianrui.qiyouriding.util.JsonUtils;
import com.dianrui.qiyouriding.util.MyOrientationListener;
import com.dianrui.qiyouriding.util.MyUtil;
import com.dianrui.qiyouriding.util.NoDoubleClickUtils;
import com.dianrui.qiyouriding.okhttp.OkHttpRequest;
import com.dianrui.qiyouriding.util.StringUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.util.Url;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.tbit.tbitblesdk.Bike.TbitBle;
import com.tbit.tbitblesdk.Bike.model.BikeState;
import com.tbit.tbitblesdk.Bike.services.command.callback.StateCallback;
import com.tbit.tbitblesdk.protocol.callback.ResultCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@SuppressWarnings("ALL")
public class RidingActivity extends BaseActivity {
    private String mIsPlays;
    private String mVehicleIds;
    private String mNumbers;
    private BaiduMap mbaiduMap;
    private boolean isMapLoaded;
    private TargetInfoModel targetInfoModel = new TargetInfoModel();
    private BluetoothAdapter mBlueadapter;
    private boolean isLocation = false;
    private JSONArray mAreaJson = null;
    private LocationBaiduClient locationBaiduClient;
    private List<BikePointModel> bikePointList = new ArrayList<>();
    private List<LatLng> mAreaPoints = new ArrayList<>();
    private int runTimes;
    private float mCurrentAccracy;
    private double mCurrentLantitude;
    private double mCurrentLongitude;
    private MyOrientationListener myOrientationListener;
    private int mXDirection;
    private String mOrderId;
    private String mVehicleStatus;
    private boolean checkMapInitFinished = false;
    private boolean checkMapAction = false;
    private boolean checkCenterAction = false;
    private boolean checkNetAction = false;
    private int checkZoomValue = 18;
    private Handler handler;
    private LatLng latLng;
    private List<Overlay> stationOverlaysList = new ArrayList<>();
    private MarkerOptions startMarkerOptions;
    private List<BitmapDescriptor> carBitDList=new ArrayList<>();
    private BitmapDescriptor bitD_NoStop;


    @BindView(R.id.top_right)
    TextView topRight;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.map)
    MapView map;
    @BindView(R.id.btn_continue)
    ImageView btnContinue;
    @BindView(R.id.btn_pause)
    ImageView btnPause;
    @BindView(R.id.btn_stop)
    ImageView btnStop;
    @BindView(R.id.bike_code)
    TextView bikeCode;

    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.riding_location)
    ImageView ridingLocation;


    @Override
    public int getContentViewId() {
        return R.layout.activity_riding;
    }


    @Override
    public void initView() {
        TbitBle.initialize(RidingActivity.this, new SecretProtocolAdapter());
        mBlueadapter = BluetoothAdapter.getDefaultAdapter();;
        mbaiduMap = map.getMap();
        BaiDuUtils.initUI(map);
        topRight.setVisibility(View.VISIBLE);
        topRight.setText(getString(R.string.custom));
        mbaiduMap.setMyLocationEnabled(true);
        customInit(true, R.color.main_color);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mVehicleIds = bundle.getString("vehicle_id");
                mNumbers = bundle.getString("number");
                mOrderId = bundle.getString("order_id");
                mVehicleStatus = bundle.getString("vehicle_status");
                mIsPlays = bundle.getString("isPlay");
            }
        }

        if (!MyUtil.isGpsEnable(RidingActivity.this)) {
            opengpsdialog();
        }
        View view1 = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.over_nostop_point, null);
        bitD_NoStop=BitmapDescriptorFactory.fromView(view1);
        //OnMapLoadedCallback这个回调可能不稳定
        mbaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                startLocation();
                checkLocationPerssions();
                currentPrice();
                initHandler();
                journey.start();
                checkMapInitFinished = true;
            }
        });
        title.setText(getString(R.string.riding));
        initOritationListener();
        myOrientationListener.start();
        pricecountDownTimer.start();
        bikeCode.setText(mNumbers);
        if ("2".equals(mVehicleStatus)) {//根据上一个页面传值判断按钮显示或者隐藏
            btnContinue.setVisibility(View.VISIBLE);
            btnPause.setVisibility(View.GONE);
        } else if ("1".equals(mVehicleStatus)) {
            btnContinue.setVisibility(View.GONE);
            btnPause.setVisibility(View.VISIBLE);
        }
        //百度地图地图状态更新监听
        mbaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
                if (i == 1) {
                    checkZoomValue = (int) mapStatus.zoom;
                    checkMapAction = true;
                } else {
                    if (checkCenterAction == true) {
                        checkMapAction = true;
                        checkCenterAction = false;
                        return;
                    }
                    checkMapAction = false;
                }
            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                if (checkMapAction == false) {
                    return;
                }
                int zoom = (int) mapStatus.zoom;
                if (checkZoomValue != zoom) {
                    return;
                }
                latLng = mapStatus.target;
                if (checkNetAction == false) {
                    getStation(mapStatus.target);
                }

            }
        });
        if ("1".equals(mIsPlays)) {
            openRawMusicLocked();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        map.onDestroy();
        bitD_NoStop.recycle();
        checkNetAction = false;
        mbaiduMap.setMyLocationEnabled(false);
        myOrientationListener.stop();
        if (locationBaiduClient != null) {
            locationBaiduClient.stop();
            locationBaiduClient = null;
        }

        if (handler != null) {
            handler.removeMessages(1);
            handler=null;
        }
        if (bikePointList != null) {
            bikePointList.clear();
            bikePointList = null;
        }

        if (mAreaPoints != null) {
            mAreaPoints.clear();
            mAreaPoints = null;
        }

        if (journey != null) {
            journey.cancel();
            journey = null;
        }
        if (pricecountDownTimer != null) {
            pricecountDownTimer.cancel();
            pricecountDownTimer = null;
        }
        if (carBitDList != null) {
            carBitDList.clear();
            carBitDList=null;
        }
        TbitBle.destroy();
        TbitBle.cancelAllCommand();
    }

    @Override
    protected void onPause() {
        super.onPause();
        map.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        map.onResume();

    }


    @Override
    protected void onRestart() {
        super.onRestart();
        startLocation();
        currentPrice();
        journeyDetail();
        if (journey != null) {
            journey.start();
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map.onSaveInstanceState(outState);

    }

    @Override
    public void initData() {}

    @OnClick({R.id.back, R.id.top_right, R.id.btn_continue, R.id.btn_pause, R.id.btn_stop, R.id.riding_findcar, R.id.riding_location})
    public void onViewClicked(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            //返回
            case R.id.back:
                EventBus.getDefault().post(new RfreshLocation());
                checkNetAction = false;
                finish();
                break;
            case R.id.top_right:
                startActivity(new Intent(RidingActivity.this, WebViewActivity.class).putExtra("type", "联系客服"));
                break;
            //按继续行驶
            case R.id.btn_continue:
                openRawMusicContinue();
                unlockContinue();
                break;
            //暂停
            case R.id.btn_pause:
                openRawMusicPause();
                lockPause();
                break;
            //立即归还.
            case R.id.btn_stop:
                lock();
                break;

            case R.id.riding_findcar:
                findCars();
                break;

            case R.id.riding_location:
                if (targetInfoModel.getLatitude() == 0.0000 && targetInfoModel.getLongitude() == 0.0000) {
                    return;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(RidingActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                BaiDuUtils.locationTarget(targetInfoModel.getLatitude(), targetInfoModel.getLongitude(), map, BaiDuUtils.getZoom(map));
                            }
                        }, 800);
                    } else {
                        ActivityCompat.requestPermissions(RidingActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
                    }
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            BaiDuUtils.locationTarget(targetInfoModel.getLatitude(), targetInfoModel.getLongitude(), map, BaiDuUtils.getZoom(map));
                        }
                    }, 800);
                }
                break;


            default:
                break;
        }
    }

    //开始定位
    public void startLocation() {
        locationBaiduClient = new LocationBaiduClient(getApplicationContext(), 2000, false, BaiDuUtils.initLocationListerer(targetInfoModel, new BaiDuUtils.OnLocationCallBack() {
            @Override
            public void onLocationSuccess(TargetInfoModel targetInfoModel) {
                RidingActivity.this.targetInfoModel = targetInfoModel;
                if (!isLocation) {
                    BaiDuUtils.locationTarget(targetInfoModel.getLatitude(), targetInfoModel.getLongitude(), map, 18f);
                    map.getMap().clear();
                    getStation(new LatLng(targetInfoModel.getLatitude(), targetInfoModel.getLongitude()));
                    getArea(targetInfoModel.getLatitude(), targetInfoModel.getLongitude(), targetInfoModel.getDistrict(), targetInfoModel.getCity(), targetInfoModel.getProvince());
                    isLocation = true;
                }
                mCurrentLantitude = targetInfoModel.getLatitude();
                mCurrentLongitude = targetInfoModel.getLongitude();
                mCurrentAccracy = targetInfoModel.getAccuracy();
                BaiDuUtils.setMyLocationData(MyLocationConfiguration.LocationMode.NORMAL,
                        true,
                        BitmapDescriptorFactory.fromResource(R.mipmap.navi_map_gps_locked),
                        R.color.main_color,
                        R.color.main_color,
                        targetInfoModel.getAccuracy(),
                        targetInfoModel.getLatitude(),
                        targetInfoModel.getLongitude(), targetInfoModel.getGetBearing(), map);

            }

            @Override
            public void onLocationFail(String errorInfo) {
            }
        }));
        locationBaiduClient.start();
    }


    private void initOritationListener() {
        myOrientationListener = new MyOrientationListener(getApplicationContext());
        myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
            @Override
            public void onOrientationChanged(float x) {
                mXDirection = (int) x;
                // 构造定位数据
                MyLocationData locData = new MyLocationData.Builder().accuracy(mCurrentAccracy).direction(mXDirection).latitude(mCurrentLantitude).longitude(mCurrentLongitude).build();
                map.getMap().setMyLocationData(locData);
                BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.mipmap.navi_map_gps_locked);
                MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker);
                map.getMap().setMyLocationConfigeration(config);
            }
        });
    }

    private void checkLocationPerssions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            } else {
                if (checkMapInitFinished == true) {
                    startLocation();
                }
            }
        } else {
            if (checkMapInitFinished == true) {
                startLocation();
            }
        }

    }

    //将返回的时间戳除以60其余后获取当前价格
    public void currentPrice() {
        JsonObject jsonObject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        OkHttpRequest.getInstance().postRequests(Url.CURRENT_PRICE, jsonObject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                runTimes = jsonObject.optJSONObject("data").optInt("run_times");
                                time.setText(jsonObject.optJSONObject("data").optString("run_time"));
                                money.setText(jsonObject.optJSONObject("data").optString("money"));
                                bikeCode.setText(jsonObject.optJSONObject("data").optString("number"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    /**
     * 获取附近的网点
     */
    @SuppressLint("InflateParams")
    private void getStation(LatLng target) {
        checkNetAction = true;
        JsonObject networksJsonobject = new JsonObject();
        networksJsonobject.addProperty("gps", target.longitude + "," + target.latitude);
        networksJsonobject.addProperty("type_id", 2);
        try {
            OkHttpRequest.getInstance().postRequests(Url.GETNETWORK, networksJsonobject.toString(), new OkHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) {
                    checkNetAction = false;
                    if (!StringUtils.isEmpty(result)) {
                        Message message = new Message();
                        try {
                            if (isFinishing()) {
                                return;
                            }
                            String status= JsonUtils.getJsonStr(result,Constant.STATUS);
                            if (Constant.DATASUCCESS.equals(status)) {

                                if (startMarkerOptions != null) {
                                    map.getMap().addOverlay(startMarkerOptions);
                                }

                                mapClear();

                                if (null != bikePointList && bikePointList.size() > 0) {
                                    bikePointList.clear();
                                }

                                String data=JsonUtils.getJsonStr(result,"data");
                                List<CarPointBean> carPointBeanList = JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<CarPointBean>>(){}.getType());
                                if(carPointBeanList == null || carPointBeanList.isEmpty()){
                                    return;
                                }
                                List<OverlayOptions> overlaysList = new ArrayList<>();
                                for (int i = 0; i < carPointBeanList.size(); i++) {
                                    CarPointBean carPointBean=carPointBeanList.get(i);
                                    BikePointModel bikePointModel = StationBean.CarToBikePoint(carPointBean);
                                    bikePointList.add(bikePointModel);
                                    if ("1".equals(carPointBean.fixed_type)) {
                                        if(carPointBean.bfixed_path == null || carPointBean.bfixed_path.isEmpty()){
                                            return;
                                        }
                                        List<LatLng> points = new ArrayList<>();
                                        for (int j = 0; j < carPointBean.bfixed_path.size(); j++) {
                                            points.add(new LatLng(carPointBean.bfixed_path.get(j).lat, carPointBean.bfixed_path.get(j).lng));
                                        }
                                        points.add(new LatLng(carPointBean.bfixed_path.get(0).lat,carPointBean.bfixed_path.get(0).lng));
                                        if (points.size() < 2) {
                                            return;
                                        }

                                        List<LatLng> overLatlngList = new ArrayList<>(points);

                                        //is_forbid是1禁停区域
                                        if ("1".equals(carPointBean.is_forbid)) {
                                            OverlayOptions ooPolyline = new PolylineOptions().width(4).color(Color.RED).points(overLatlngList).dottedLine(true);
                                            overlaysList.add(ooPolyline);

                                            OverlayOptions ooPolygon1 = new PolygonOptions().points(overLatlngList).fillColor(Color.argb(46, 255, 0, 0));
                                            overlaysList.add(ooPolygon1);

                                            OverlayOptions markerOptions = new MarkerOptions().position(new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng)).icon(bitD_NoStop);
                                            overlaysList.add(markerOptions);

                                        }else{
                                            OverlayOptions overlayOptions = new PolylineOptions().width(4).color(getResources().getColor(R.color.main_color)).points(overLatlngList).dottedLine(true);
                                            overlaysList.add(overlayOptions);
                                            //填充
                                            OverlayOptions ooPolygon = new PolygonOptions().points(overLatlngList).fillColor(Color.argb(46, 255, 186, 0));
                                            overlaysList.add(ooPolygon);
                                        }
                                    } else if ("0".equals(carPointBean.fixed_type)) {
                                        int networkRange = Integer.parseInt(carPointBean.network_range);
                                        LatLng center = new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng);
                                        CircleOptions circleOptions = new CircleOptions();
                                        circleOptions.center(center);//设置圆心坐标
                                        circleOptions.fillColor(Color.argb(36, 255, 186, 0));//圆的填充颜色
                                        circleOptions.radius(networkRange);//设置半径
                                        overlaysList.add(circleOptions);
                                    }
                                }
                                if (overlaysList.size() > 0) {
                                    stationOverlaysList.addAll(mbaiduMap.addOverlays(overlaysList));
                                }
                                message.what = 1;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        handler.sendMessage(message);
                    }
                }

                @Override
                public void failedRequest(String result) {
                    checkNetAction = false;
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        List<OverlayOptions> list = new ArrayList<>();
                        for (int i = 0; i < bikePointList.size(); i++) {
                            Bundle bundle = new Bundle();
                            bundle.putDouble("lat", bikePointList.get(i).blat);
                            bundle.putDouble("lng", bikePointList.get(i).blng);
                            bundle.putString("vehicle_number", bikePointList.get(i).vehicle_number);

                            if (bikePointList.get(i).is_forbid.equals("0")) {

                                View view = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.over_elecar_point, null);

                                TextView markernum = view.findViewById(R.id.station_number_blue_dot);
                                int number = Integer.parseInt(bikePointList.get(i).vehicle_number);
                                if (number > 9) {
                                    String showMarkernumplus = 9 + "+" + "";
                                    markernum.setText(showMarkernumplus);
                                } else {
                                    String showVehicleNumber = bikePointList.get(i).vehicle_number + "";
                                    markernum.setText(showVehicleNumber);
                                }

                                BitmapDescriptor BitDCar=BitmapDescriptorFactory.fromView(view);
                                OverlayOptions markerOptions = new MarkerOptions().position(new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng)).icon(BitDCar).extraInfo(bundle).zIndex(10);
                                carBitDList.add(BitDCar);
                                list.add(markerOptions);
                            }
                        }
                        if (list.size() > 0) {
                            stationOverlaysList.addAll(map.getMap().addOverlays(list));
                        }
                        break;

                    default:
                        break;
                }


            }
        };
    }

    //自定义清除地图的覆盖物
    private void mapClear() {
        if(carBitDList.size()>0){
            for(BitmapDescriptor bitmapDescriptor:carBitDList){
                bitmapDescriptor.recycle();
            }
            carBitDList.clear();
        }

        if (stationOverlaysList.size() > 0) {
            for (Overlay overlay : stationOverlaysList) {
                overlay.remove();
            }
            stationOverlaysList.clear();
        }
    }

    CountDownTimerUtils journey = new CountDownTimerUtils(Long.MAX_VALUE, 10000) {
        @Override
        public void onTick(long millisUntilFinished) {
            journeyDetail();
        }

        @Override
        public void onFinish() {
        }
    };

    //获取起点(永远显示一个),10秒刷一次
    private void journeyDetail() {
        JsonObject journey = new JsonObject();
        journey.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        OkHttpRequest.getInstance().postRequests(Url.JOURNEY_DETAILS, journey.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("gps");
                                if (jsonArray.length() > 0) {
                                    if (startMarkerOptions == null) {
                                        View startPointView = LayoutInflater.from(RidingActivity.this).inflate(R.layout.start_point, null);
                                        startMarkerOptions = new MarkerOptions();
                                        startMarkerOptions.position(new LatLng(jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("lat"), jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("lng"))).icon(BitmapDescriptorFactory.fromBitmap(MyUtil.getViewBitmap(startPointView))).zIndex(100);
                                        map.getMap().addOverlay(startMarkerOptions);
                                    } else {
                                        startMarkerOptions.position(new LatLng(jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("lat"), jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("lng")));
                                    }
                                    mapClear();
                                    getStation(new LatLng(jsonArray.optJSONObject(0).optDouble("lat"), jsonArray.optJSONObject(0).optDouble("lng")));
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    //每1秒走定时器
    CountDownTimerUtils pricecountDownTimer = new CountDownTimerUtils(Long.MAX_VALUE, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            runTimes++;
            String showTime = MyUtil.FormatMiss(runTimes);
            time.setText(showTime);
            if (runTimes % 61 == 0) {
                currentPrice();
            }
        }

        @Override
        public void onFinish() {
        }
    };


    //一键寻车
    private void findCars() {
        JsonObject findCar = new JsonObject();
        findCar.addProperty("vehicle_id", mVehicleIds);
        OkHttpRequest.getInstance().postRequests(Url.FINDCAR, findCar.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));

                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }


    //电子围栏
    public void getArea(double latitude, double longitude, String district, String city, String province) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("gps", longitude + "," + latitude);
        jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        jsonObject.addProperty("district", district);
        jsonObject.addProperty("city", city);
        jsonObject.addProperty("province", province);
        OkHttpRequest.getInstance().postRequests(Url.AREA, jsonObject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                if (mAreaPoints != null) {
                                    mAreaPoints.clear();
                                }
                                JSONArray jsonArray3 = jsonObject.optJSONArray("data");
                                if (jsonArray3.length() > 0) {
                                    JSONObject jsonObject1 = jsonArray3.optJSONObject(0);
                                    String areaIds = jsonObject1.optString("area_id");
                                    SPUtils.getInstance().put("area_id", areaIds);
                                    mAreaJson = jsonObject1.optJSONArray("bfixed_path");
                                    SPUtils.getInstance().put("area_data", String.valueOf(mAreaJson));
                                    drawArea();
                                }
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //画电子围栏
    public void drawArea() {
        JSONArray jsonArray1 = mAreaJson;
        if (jsonArray1.length() > 0) {
            for (int j = 0; j < jsonArray1.length(); j++) {
                if (j == jsonArray1.length()) {
                    JSONObject jsonObject2 = jsonArray1.optJSONObject(0);
                    mAreaPoints.add(new LatLng(jsonObject2.optDouble("lat"), jsonObject2.optDouble("lng")));
                } else {
                    JSONObject jsonObject2 = jsonArray1.optJSONObject(j);
                    mAreaPoints.add(new LatLng(jsonObject2.optDouble("lat"), jsonObject2.optDouble("lng")));
                }
            }
            if (mAreaPoints.size() < 2) {
                return;
            }

            if (mAreaPoints.size() > 0) {
                List<BitmapDescriptor> picList = new ArrayList<>();
                picList.add(BitmapDescriptorFactory.fromResource(R.mipmap.area_img));

                List<Integer> textureIndexs = new ArrayList<>();
                textureIndexs.add(0);
                OverlayOptions ooPolyline11 = new PolylineOptions()
                        .width(14)
                        .points(mAreaPoints)
                        .dottedLine(true)
                        .textureIndex(textureIndexs).
                                customTextureList(picList);
                mbaiduMap.addOverlay(ooPolyline11);
            }
        }
    }


    @SuppressLint("InflateParams")
    //继续用车
    private void unlockContinue() {
        showLoadingDialog(getString(R.string.revert_continue));
        JsonObject continues = new JsonObject();
        continues.addProperty("vehicle_id", mVehicleIds);
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            continues.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        continues.addProperty("app_type", "1");//客户端类型：1安卓，2IOS，3微信小程序，4支付宝小程序
        continues.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());//手机机型
        continues.addProperty("app_version", MyUtil.getAppInfo(RidingActivity.this));//客户端版本
        continues.addProperty("type", 0);
        try {
            OkHttpRequest.getInstance().postRequests(Url.CONTINUE, continues.toString(), new OkHttpRequest.XCallBack() {

                @Override
                public void onResponse(String response) {
                    if (!StringUtils.isEmpty(response)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(response);
                            if (null != jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    if ("1".equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {
                                        btnPause.setVisibility(View.VISIBLE);
                                        btnContinue.setVisibility(View.GONE);
                                        EventBus.getDefault().post(new RfreshOrder());
                                    }
                                } else {
                                    dismissLoadingDialog();
                                    if (jsonObject.optJSONObject("data").optInt("type") == 1) {//type是1的话用蓝牙借车
                                        AlertDialog.Builder builder = new AlertDialog.Builder(RidingActivity.this, R.style.activity_dialog);
                                        View view = LayoutInflater.from(RidingActivity.this).inflate(R.layout.blue_endcar_dialog, null);
                                        final AlertDialog conituredialog = builder.create();
                                        conituredialog.setView(view);
                                        conituredialog.show();
                                        final TextView contents = view.findViewById(R.id.content);
                                        final Button endCarstartCars = view.findViewById(R.id.start_cars);
                                        final Button cancel = view.findViewById(R.id.cancel);
                                        contents.setText(jsonObject.optString("message"));
                                        cancel.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                conituredialog.dismiss();
                                            }
                                        });
                                        endCarstartCars.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                conituredialog.dismiss();
                                                if (!mBlueadapter.isEnabled()) {
                                                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                                                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                                                } else {
                                                    showLoadingDialog("正在连接蓝牙中,请稍候...");
                                                    connectBlueTeeth(jsonObject.optJSONObject("data").optString("device"), jsonObject.optJSONObject("data").optString("token"),"2");



                                                }
                                            }
                                        });
                                    }else {
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            dismissLoadingDialog();
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    dismissLoadingDialog();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("InflateParams")
    //暂停用车
    private void lockPause() {
        showLoadingDialog(getString(R.string.revert_pause));
        JsonObject pause = new JsonObject();
        pause.addProperty("vehicle_id", mVehicleIds);
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            pause.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        pause.addProperty("app_type", "1");//客户端类型：1安卓，2IOS，3微信小程序，4支付宝小程序
        pause.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());//手机机型
        pause.addProperty("app_version", MyUtil.getAppInfo(RidingActivity.this));//客户端版本
        pause.addProperty("type", 0);
        OkHttpRequest.getInstance().postRequests(Url.PAUSE, pause.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                if ("2".equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {
                                    btnPause.setVisibility(View.GONE);
                                    btnContinue.setVisibility(View.VISIBLE);
                                    EventBus.getDefault().post(new RfreshOrder());

                                }
                            } else {
                                dismissLoadingDialog();
                                if (jsonObject.optJSONObject("data").optInt("type") == 1) {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(RidingActivity.this, R.style.activity_dialog);
                                    View view = LayoutInflater.from(RidingActivity.this).inflate(R.layout.blue_endcar_dialog, null);
                                    final AlertDialog conituredialog = builder.create();
                                    conituredialog.setView(view);
                                    conituredialog.show();
                                    final TextView contents = view.findViewById(R.id.content);
                                    final Button endCarstartCars = view.findViewById(R.id.start_cars);
                                    final Button cancel = view.findViewById(R.id.cancel);
                                    contents.setText(jsonObject.optString("message"));
                                    cancel.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            conituredialog.dismiss();
                                        }
                                    });
                                    endCarstartCars.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            conituredialog.dismiss();
                                            if (!mBlueadapter.isEnabled()) {
                                                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                                                ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                                            } else {
                                                connectBlueTeeth(jsonObject.optJSONObject("data").optString("device"), jsonObject.optJSONObject("data").optString("token"),"1");
                                            }

                                        }
                                    });
                                }else {
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @SuppressLint("InflateParams")
    //还车
    private void lock() {
        showLoadingDialog(getString(R.string.revert_car));
        final JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("vehicle_id", mVehicleIds);
        jsonObject.addProperty("gps", targetInfoModel.getLongitude() + "," + targetInfoModel.getLatitude());
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        jsonObject.addProperty("app_type", "1");//客户端类型：1安卓，2IOS，3微信小程序，4支付宝小程序
        jsonObject.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());//手机机型
        jsonObject.addProperty("app_version", MyUtil.getAppInfo(RidingActivity.this));//客户端版本
        jsonObject.addProperty("type", 0);
        OkHttpRequest.getInstance().postRequests(Url.STOP, jsonObject.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonobject = new JSONObject(response);
                        if (null != jsonobject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonobject.optString("status"))) {
                                dismissLoadingDialog();
                                if (locationBaiduClient != null) {
                                    locationBaiduClient.stop();
                                }
                                if (pricecountDownTimer != null) {
                                    pricecountDownTimer.cancel();
                                }
                                if (journey != null) {
                                    journey.cancel();
                                }
                                checkNetAction = false;
                                Intent intent2 = new Intent(RidingActivity.this, RidingPriceActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("id", jsonobject.optJSONObject("data").optString("order_id"));
                                bundle.putString("number", mNumbers);
                                bundle.putString("isPayPlays", "1");
                                intent2.putExtras(bundle);
                                startActivity(intent2);
                                TbitBle.disConnect();
                                TbitBle.cancelAllCommand();
                                EventBus.getDefault().post(new PaymentEvent());
                                EventBus.getDefault().post(new RfreshOrder());
                                finish();
                            } else {
                                dismissLoadingDialog();
                                if (jsonobject.optJSONObject("data").optInt("type") == 1) {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(RidingActivity.this, R.style.activity_dialog);
                                    View view = LayoutInflater.from(RidingActivity.this).inflate(R.layout.blue_endcar_dialog, null);
                                    final AlertDialog dialog = builder.create();
                                    dialog.setView(view);
                                    dialog.show();
                                    final TextView contents = view.findViewById(R.id.content);
                                    final Button endCarstartCars = view.findViewById(R.id.start_cars);
                                    final Button cancel = view.findViewById(R.id.cancel);
                                    contents.setText(jsonobject.optString("message"));
                                    cancel.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            dialog.dismiss();
                                        }
                                    });
                                    endCarstartCars.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (!mBlueadapter.isEnabled()) {//使用蓝牙前先判断用户是否打开蓝牙
                                                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                                                ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                                            } else {
                                                dialog.dismiss();
                                                connectBlueTeeth(jsonobject.optJSONObject("data").optString("device"), jsonobject.optJSONObject("data").optString("token"),"3");

                                            }

                                        }
                                    });

                                } else if (jsonobject.optJSONObject("data").optInt("type") == 2) {  //不在站点确定还车
                                    AlertDialog.Builder builder = new AlertDialog.Builder(RidingActivity.this, R.style.activity_dialog);
                                    View view = LayoutInflater.from(RidingActivity.this).inflate(R.layout.redpocket_dialog, null);
                                    final AlertDialog nostastiondialog = builder.create();
                                    nostastiondialog.setView(view);
                                    nostastiondialog.setCanceledOnTouchOutside(false);
                                    nostastiondialog.show();

                                    final TextView shownostation_txt = view.findViewById(R.id.shownostation_txt);
                                    shownostation_txt.setText(jsonobject.optString("message"));//后台返回message
                                    final Button nostationsure = view.findViewById(R.id.nostationsure);
                                    final Button cancels = view.findViewById(R.id.cancel);

                                    cancels.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            nostastiondialog.dismiss();
                                        }
                                    });
                                    nostationsure.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            nostastiondialog.dismiss();
                                            redPocketlock();
                                        }
                                    });
                                }else {
                                    Toast.makeText(RidingActivity.this, jsonobject.optString("message"), Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                btnPause.setEnabled(true);
                btnContinue.setEnabled(true);
                btnStop.setEnabled(true);
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    //不在站点确定还车(收调度费)
    private void redPocketlock() {
        showLoadingDialog(getString(R.string.revert_car));
        final JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("vehicle_id", mVehicleIds);
        jsonObject.addProperty("gps", targetInfoModel.getLongitude() + "," + targetInfoModel.getLatitude());
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        jsonObject.addProperty("app_type", "1");//客户端类型：1安卓，2IOS，3微信小程序，4支付宝小程序
        jsonObject.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());//手机机型
        jsonObject.addProperty("app_version", MyUtil.getAppInfo(RidingActivity.this));//客户端版本
        jsonObject.addProperty("type", 2);
        OkHttpRequest.getInstance().postRequests(Url.STOP, jsonObject.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonobject = new JSONObject(response);
                        if (null != jsonobject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonobject.optString("status"))) {
                                dismissLoadingDialog();
                                if (locationBaiduClient != null) {
                                    locationBaiduClient.stop();
                                }
                                if (pricecountDownTimer != null) {
                                    pricecountDownTimer.cancel();
                                }
                                if (journey != null) {
                                    journey.cancel();
                                }
                                Intent intent2 = new Intent(RidingActivity.this, RidingPriceActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("id", jsonobject.optJSONObject("data").optString("order_id"));
                                bundle.putString("number", mNumbers);
                                bundle.putString("isPayPlays", "1");
                                intent2.putExtras(bundle);
                                startActivity(intent2);
                                EventBus.getDefault().post(new PaymentEvent());
                                EventBus.getDefault().post(new RfreshOrder());
                                finish();
                            } else {
                                dismissLoadingDialog();
                                btnPause.setEnabled(true);
                                btnContinue.setEnabled(true);
                                btnStop.setEnabled(true);
                                if (jsonobject.optJSONObject("data").optInt("type") == 1) {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(RidingActivity.this, R.style.activity_dialog);
                                    View view = LayoutInflater.from(RidingActivity.this).inflate(R.layout.blue_endcar_dialog, null);
                                    final AlertDialog dialog = builder.create();
                                    dialog.setView(view);
                                    dialog.show();
                                    final TextView contents = view.findViewById(R.id.content);
                                    final Button endCarstartCars = view.findViewById(R.id.start_cars);
                                    final Button cancel = view.findViewById(R.id.cancel);
                                    contents.setText(jsonobject.optString("message"));
                                    cancel.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            dialog.dismiss();
                                        }
                                    });
                                    endCarstartCars.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (!mBlueadapter.isEnabled()) {
                                                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                                                ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                                            } else {
                                                dialog.dismiss();

                                                connectStopBlueTeeth(jsonobject.optJSONObject("data").optString("device"), jsonobject.optJSONObject("data").optString("token"));

                                            }

                                        }
                                    });

                                } else if (jsonobject.optJSONObject("data").optInt("type") == 2) {//types是2要收调度费
                                    AlertDialog.Builder builder = new AlertDialog.Builder(RidingActivity.this, R.style.activity_dialog);
                                    View view = LayoutInflater.from(RidingActivity.this).inflate(R.layout.redpocket_dialog, null);
                                    final AlertDialog nostastiondialog = builder.create();
                                    nostastiondialog.setView(view);
                                    nostastiondialog.setCanceledOnTouchOutside(false);
                                    nostastiondialog.show();

                                    final TextView shownostation_txt = view.findViewById(R.id.shownostation_txt);
                                    shownostation_txt.setText(jsonobject.optString("message"));//后台返回message
                                    final Button nostationsure = view.findViewById(R.id.nostationsure);
                                    final Button cancels = view.findViewById(R.id.cancel);

                                    cancels.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            nostastiondialog.dismiss();
                                        }
                                    });
                                    nostationsure.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            nostastiondialog.dismiss();
                                            redPocketlock();
                                        }
                                    });
                                }else {
                                    Toast.makeText(RidingActivity.this, jsonobject.optString("message"), Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                btnPause.setEnabled(true);
                btnContinue.setEnabled(true);
                btnStop.setEnabled(true);
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //蓝牙连接，第一个设备编号，第二个密钥，第三个作为不同功能指令区分
    private void connectBlueTeeth(String deviceNumber, String token, final String blueCommandType) {
        showLoadingDialog("正在连接蓝牙中...请稍候");
        TbitBle.connect(deviceNumber, token, new ResultCallback() {

            @Override
            public void onResult(int resultCode) {
                if (resultCode == 0) {
                    dismissLoadingDialog();
                    if (blueCommandType.equals("1")) {//暂停
                        lockDevice();
                        bluePauseCar();
                    } else if (blueCommandType.equals("2")) {//继续
                        unlockDevice();
                        blueContinueRidingCar();
                    } else if (blueCommandType.equals("3")) {//停止
                        lockDevice();
                        BlueStopCar();
                    }
                }
            }
        }, new StateCallback() {
            @Override
            public void onStateUpdated(BikeState bikeState) {

            }
        });
    }



    //蓝牙连接，参数为设备编号，密钥（后台提供）
    private void connectPauseBlueTeeth(String deviceNumber, String key) {
        TbitBle.connect(deviceNumber, key, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 连接回应
                Log.e("连接回应状态码-->", resultCode + "");
                if (resultCode == 0) {
                    dismissLoadingDialog();
                    lockDevice();//连接成功发送指令
                    bluePauseCar();
                }else {
                    dismissLoadingDialog();
                    ToastUtil.showToast("错误码: " + resultCode + " 蓝牙连接失败，请重新再试");
                }
            }
        }, new StateCallback() {
            @Override
            public void onStateUpdated(BikeState bikeState) { }
        });
    }

    private void connectContiueBlueTeeth(String deviceNumber, String key) {
        TbitBle.connect(deviceNumber, key, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 连接回应
                Log.e("连接回应状态码-->", resultCode + "");
                if (resultCode == 0) {
                    dismissLoadingDialog();
                    unlockDevice();
                    blueContinueRidingCar();
                } else {
                    dismissLoadingDialog();
                    ToastUtil.showToast("错误码: " + resultCode + " 蓝牙连接失败，请重新再试");
                }
            }
        }, new StateCallback() {
            @Override
            public void onStateUpdated(BikeState bikeState) {}
        });
    }


    private void connectStopBlueTeeth(String deviceNumber, String key) {
        TbitBle.connect(deviceNumber, key, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 连接回应
                Log.e("连接成功后回应状态码-->", resultCode + "");
                if (resultCode == 0) {
                    dismissLoadingDialog();
                    lockDevice();
                    BlueStopCar();
                } else {
                    dismissLoadingDialog();
                    ToastUtil.showToast("错误码: " + resultCode + " 蓝牙连接失败，请重新再试");
                }
            }
        }, new StateCallback() {
            @Override
            public void onStateUpdated(BikeState bikeState) {

            }
        });
    }

    // 解锁
    private void unlockDevice() {
        TbitBle.unlock(new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 解锁回应
                Log.e("解锁回应-->", resultCode + "");
            }
        });
    }

    // 上锁
    private void lockDevice() {
        TbitBle.lock(new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 上锁回应
                Log.e("上锁回应-->", resultCode + "");
            }
        });
    }

    //暂停后蓝牙发送命令后回传给服务器就是type传1即可
    private void bluePauseCar() {
        showLoadingDialog(SPUtils.getInstance().getString("unlock"));
        final JsonObject bluePause = new JsonObject();
        bluePause.addProperty("vehicle_id", mVehicleIds);
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            bluePause.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        bluePause.addProperty("app_type", "1");//客户端类型：1安卓，2IOS，3微信小程序，4支付宝小程序
        bluePause.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());//手机机型
        bluePause.addProperty("app_version", MyUtil.getAppInfo(RidingActivity.this));//客户端版本
        bluePause.addProperty("type", 1);//非必传（type==1）蓝牙还车
        OkHttpRequest.getInstance().postRequests(Url.PAUSE, bluePause.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    dismissLoadingDialog();
                    try {
                        final JSONObject bluePause = new JSONObject(response);
                        if (null != bluePause && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(bluePause.optString("status"))) {
                                if ("2".equals(bluePause.optJSONObject("data").optString("vehicle_status"))) {
                                    btnPause.setVisibility(View.GONE);
                                    btnContinue.setVisibility(View.VISIBLE);
                                    EventBus.getDefault().post(new RfreshOrder());
                                }
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(bluePause.optString("message"));

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //继续蓝牙发送命令后回传给服务器就是type传1即可
    private void blueContinueRidingCar() {
        showLoadingDialog(SPUtils.getInstance().getString("unlock"));
        JsonObject continues = new JsonObject();
        continues.addProperty("vehicle_id", mVehicleIds);
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            continues.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        continues.addProperty("app_type", "1");//客户端类型：1安卓，2IOS，3微信小程序，4支付宝小程序
        continues.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());//手机机型
        continues.addProperty("app_version", MyUtil.getAppInfo(RidingActivity.this));//客户端版本
        continues.addProperty("type", 1);
        OkHttpRequest.getInstance().postRequests(Url.CONTINUE, continues.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    dismissLoadingDialog();
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                if ("1".equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {
                                    btnPause.setVisibility(View.VISIBLE);
                                    btnContinue.setVisibility(View.GONE);
                                    EventBus.getDefault().post(new RfreshOrder());
                                }
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    //蓝牙发送指令还车
    private void BlueStopCar() {
        showLoadingDialog(getString(R.string.revert_car));
        JsonObject stopJSONObject = new JsonObject();
        stopJSONObject.addProperty("vehicle_id", mVehicleIds);
        stopJSONObject.addProperty("gps", targetInfoModel.getLongitude() + "," + targetInfoModel.getLatitude());
        stopJSONObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        stopJSONObject.addProperty("app_type", "1");//客户端类型：1安卓，2IOS，3微信小程序，4支付宝小程序
        stopJSONObject.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());//手机机型
        stopJSONObject.addProperty("app_version", MyUtil.getAppInfo(RidingActivity.this));//客户端版本
        stopJSONObject.addProperty("type", 1);
        OkHttpRequest.getInstance().postRequests(Url.STOP, stopJSONObject.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject stopJSONObject = new JSONObject(response);
                        if (null != stopJSONObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(stopJSONObject.optString("status"))) {
                                dismissLoadingDialog();
                                if (locationBaiduClient != null) {
                                    locationBaiduClient.stop();
                                }
                                if (pricecountDownTimer != null) {
                                    pricecountDownTimer.cancel();
                                }
                                if (journey != null) {
                                    journey.cancel();
                                }
                                Intent intent2 = new Intent(RidingActivity.this, RidingPriceActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("id", stopJSONObject.optJSONObject("data").optString("order_id"));
                                bundle.putString("number", mNumbers);
                                bundle.putString("isPayPlays", "1");
                                intent2.putExtras(bundle);
                                startActivity(intent2);
                                EventBus.getDefault().post(new PaymentEvent());
                                EventBus.getDefault().post(new RfreshOrder());
                                TbitBle.disConnect();
                                TbitBle.cancelAllCommand();
                                finish();
                            } else {
                                dismissLoadingDialog();
                                Toast.makeText(RidingActivity.this, stopJSONObject.optString("message"), Toast.LENGTH_SHORT).show();

                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));

            }
        });
    }

    /**
     * 打开GPS对话框
     */
    private void opengpsdialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(RidingActivity.this, R.style.RcDialog);
        final View view2 = LayoutInflater.from(RidingActivity.this).inflate(R.layout.open_gps_dialog, null);
        final AlertDialog pausedialog = builder.create();
        pausedialog.setView(view2);
        pausedialog.setCanceledOnTouchOutside(false);
        pausedialog.show();
        final Button yes = view2.findViewById(R.id.yes);

        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pausedialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 6);
            }
        });
    }

    private void openRawMusicLocked() {
        MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.carlocked);
        mediaPlayer1.start();
    }


    //暂停用车的语音
    private void openRawMusicPause() {
        MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.pause);
        mediaPlayer1.start();
    }

    //继续用车的语音
    private void openRawMusicContinue() {
        MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.continuecar);
        mediaPlayer1.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startLocation();
                }
                break;
            case 2:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        BaiDuUtils.locationTarget(targetInfoModel.getLatitude(), targetInfoModel.getLongitude(), map, BaiDuUtils.getZoom(map));
                    }
                }, 1000);
                break;

            default:
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            EventBus.getDefault().post(new RfreshLocation());
            checkNetAction = false;
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
